package io.rong.imkit.webview

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.os.Message
import android.view.KeyEvent
import android.webkit.*
import com.custom.base.util.TANetWorkUtil

class DefaultWebViewClient : WebViewClient() {
    private var listener: WebViewClientListener? = null
    var isImgSrcClik = false
    private var webView: CustomWebView? = null
    fun setListener(
        listener: WebViewClientListener?,
        customWebView: CustomWebView?,
        isImgSrcClik: Boolean
    ) {
        this.listener = listener
        webView = customWebView
        this.isImgSrcClik = isImgSrcClik
    }

    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        return if (listener != null) {
            listener!!.shouldOverrideUrlLoading(view, url)
        } else {
            if (!TANetWorkUtil.isNetworkAvailable(view.context)) {
//                SDToast.showToast("亲!您的网络状况不太好!");
                true
            } else {
                if (url.startsWith("tel:")) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    view.context.startActivity(intent)
                    return true
                }
                if (url.startsWith("weixin://wap/pay?")) {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.data = Uri.parse(url)
                    view.context.startActivity(intent)
                    return true
                }
                if (url.startsWith("appay://appayservice/?")) {
                    val intent = Intent()
                    intent.action = Intent.ACTION_VIEW
                    intent.data = Uri.parse(url)
                    view.context.startActivity(intent)
                    return true
                }
                view.loadUrl(url)
                true
            }
        }
    }

    override fun onReceivedError(
        view: WebView?,
        errorCode: Int,
        description: String?,
        failingUrl: String?
    ) {
        if (listener != null) {
            listener!!.onReceivedError(view, errorCode, description, failingUrl)
        } else {
            failingUrl?.apply {
                view?.loadUrl(this)
            }
        }
    }

    override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
        listener?.onPageStarted(view, url, favicon)
    }

    override fun onPageFinished(view: WebView?, url: String?) {
        listener?.onPageFinished(view, url)
        if (isImgSrcClik) { //获取网页中所有图片
            webView?.loadUrl(
                """javascript:(function(){
                        var objs = document.querySelectorAll(".tg_list_main li img");
                        var json = [];
                        for(var i=0;i<objs.length;i++){
                            json.push({index:i,src:objs[i].src});
                            objs[i].index = i;
                            objs[i].onclick = function() {
                                window.App.setImgSrc(this.index,JSON.stringify(json));  				
                            };
                        }
                    })()"""
            )
        }
    }

    override fun onLoadResource(view: WebView, url: String) {
        listener?.onLoadResource(view, url)
    }

    @Deprecated("")
    override fun onTooManyRedirects(
        view: WebView,
        cancelMsg: Message,
        continueMsg: Message
    ) {
        listener?.onTooManyRedirects(view, cancelMsg, continueMsg)
    }

    override fun onFormResubmission(
        view: WebView,
        dontResend: Message,
        resend: Message
    ) {
        listener?.onFormResubmission(view, dontResend, resend)
        super.onFormResubmission(view, dontResend, resend)
    }

    override fun doUpdateVisitedHistory(
        view: WebView,
        url: String,
        isReload: Boolean
    ) {
        listener?.doUpdateVisitedHistory(view, url, isReload)
    }

    override fun onReceivedSslError(
        view: WebView,
        handler: SslErrorHandler,
        error: SslError
    ) {
        listener?.onReceivedSslError(view, handler, error)
        super.onReceivedSslError(view, handler, error)
    }

    override fun onReceivedHttpAuthRequest(
        view: WebView,
        handler: HttpAuthHandler,
        host: String,
        realm: String
    ) {
        listener?.onReceivedHttpAuthRequest(view, handler, host, realm)
        super.onReceivedHttpAuthRequest(view, handler, host, realm)
    }

    override fun shouldOverrideKeyEvent(
        view: WebView,
        event: KeyEvent
    ): Boolean {
        return if (listener != null) {
            listener!!.shouldOverrideKeyEvent(view, event)
        } else {
            super.shouldOverrideKeyEvent(view, event)
        }
    }

    override fun onUnhandledKeyEvent(view: WebView, event: KeyEvent) {
        listener?.onUnhandledKeyEvent(view, event)
        super.onUnhandledKeyEvent(view, event)
    }

    override fun onScaleChanged(
        view: WebView,
        oldScale: Float,
        newScale: Float
    ) {
        listener?.onScaleChanged(view, oldScale, newScale)
    }

    override fun onReceivedLoginRequest(
        view: WebView,
        realm: String,
        account: String?,
        args: String
    ) {
        listener?.onReceivedLoginRequest(view, realm, account, args)
    }
}